import 'dart:convert';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_yres/model/shop/hdk_list_model.dart';
import 'package:dio/dio.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/pages/shop/shop_detail_page.dart';
import 'package:cached_network_image/cached_network_image.dart';

class HDKListPage extends StatefulWidget {
  String type;
  String name;
  String cid;
//   type=1是今日上新（当天新券商品），type=2是9.9包邮，
// type=3是30元封顶，
// type=4是聚划算，
// type=5是淘抢购，
// type=6是0点过夜单，
// type=7是预告单，
// type=8是品牌单，
// type=9是天猫商品，
// type=10是视频单
  HDKListPage({Key key, this.type, this.name, this.cid}) : super(key: key);

  @override
  _HDKListPageState createState() => _HDKListPageState();
}

class _HDKListPageState extends State<HDKListPage> {
  List<HDKListModelData> shopData = []; //商品数组
  EasyRefreshController _controller = new EasyRefreshController();
  var min_id = 1; //分页

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        // appBar: AppBar(
        //   title:
        //       Text(widget.name, style: TextStyle(fontSize: 18, color: black)),
        //   backgroundColor: white,
        //   brightness: Brightness.light,
        //   iconTheme: IconThemeData(color: black_99),
        //   elevation: 1.0,
        // ),
        body: Container(
      child: new EasyRefresh(
        //刷新  加载组件
        controller: _controller,
        child: CustomScrollView(slivers: <Widget>[
          // SliverToBoxAdapter(
          //   child: Container(
          //     margin: EdgeInsets.fromLTRB(
          //         0, ScreenUtil.getInstance().setWidth(15), 0, 0),
          //     child: Image.asset('images/icon_hot.png', fit: BoxFit.fitWidth),
          //   ),
          // ),
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) -
                      ScreenUtil.getInstance().setWidth(20)) /
                  2,
              mainAxisSpacing: 10.0,
              crossAxisSpacing: 15.0,
              childAspectRatio: 0.55, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return getItemContainer(context, index);
              },
              childCount: shopData.length,
            ),
          ),
        ]),
        onRefresh: () async {
          min_id = 1;
          getHDKGoodsListUrl();
        },
        onLoad: () async {
          getHDKGoodsListUrl();
        },
      ),
    ));
  }

//商品cell
  getItemContainer(BuildContext context, int index) {
    HDKListModelData model = shopData[index];
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(text: model.itemendprice, style: TextStyle(fontSize: 18.0)),
        TextSpan(
          text: model.itemprice,
          style: TextStyle(
              fontSize: 12.0,
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var quanHeader = Container(
      width: ScreenUtil.getInstance().setWidth(40),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_header.png"),
          fit: BoxFit.cover,
        ),
      ),
    );
    var quan = Container(
      // width: ScreenUtil.getInstance().setWidth(75),
      height: ScreenUtil.getInstance().setWidth(34),
      padding: EdgeInsets.only(right: 10),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_footer.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Center(
          child: Text(
        model.couponmoney + '元',
        style: TextStyle(color: Colors.white, fontSize: 10),
      )),
    );
    var yongjin = Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20), 0,
          ScreenUtil.getInstance().setWidth(10), 0),
      height: ScreenUtil.getInstance().setWidth(34),
      color: Color.fromRGBO(250, 226, 226, 1),
      child: Center(
          child: Text('预估赚¥' + formatNum((double.parse(model.tkrates)/100*double.parse(model.itemendprice)),2).toString() ,
              style: TextStyle(color: Colors.red, fontSize:ScreenUtil.getInstance().setSp(20)))),
    );
    return GestureDetector(
      child: Container(
          color: Colors.white,
          margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(10), 0,
              ScreenUtil.getInstance().setWidth(10), 0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              CachedNetworkImage(
                width: (ScreenUtil.getInstance().setWidth(750) -
                        ScreenUtil.getInstance().setWidth(20)) /
                    2,
                height: (ScreenUtil.getInstance().setWidth(750) -
                        ScreenUtil.getInstance().setWidth(20)) /
                    2,
                fit: BoxFit.fill,
                imageUrl: model.itempic,
                placeholder: (context, url) => Image.asset(
                  'images/pic_default.png',
                  fit: BoxFit.fill,
                  width: (ScreenUtil.getInstance().setWidth(750) -
                          ScreenUtil.getInstance().setWidth(20)) /
                      2,
                  height: (ScreenUtil.getInstance().setWidth(750) -
                          ScreenUtil.getInstance().setWidth(20)) /
                      2,
                ),
                errorWidget: (context, url, error) => Image.asset(
                  'images/pic_default.png',
                  fit: BoxFit.fill,
                  width: (ScreenUtil.getInstance().setWidth(750) -
                          ScreenUtil.getInstance().setWidth(20)) /
                      2,
                  height: (ScreenUtil.getInstance().setWidth(750) -
                          ScreenUtil.getInstance().setWidth(20)) /
                      2,
                ),
              ),
              Text(model.itemtitle, maxLines: 2),
              Container(
                margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                child: price,
              ),
              Container(
                margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                child: Text('已售' + model.itemsale,
                    style: TextStyle(fontSize: 12.0, color: Colors.grey)),
              ),
              Container(
                margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      flex: 2,
                      child: Row(
                        children: <Widget>[quanHeader, quan],
                      ),
                    ),
                    Expanded(flex: 2, child: yongjin)
                  ],
                ),
              )
            ],
          )),
      onTap: () {
        print(model.itemid);
        Navigator.push(
            context,
            MaterialPageRoute(
                //导航打开新视图
                builder: (context) =>
                    ShopDetailPage(hdkmodel: model) //打开第二个页面，并传值，传递值的名称是model
                ));
      },
    );
  }

    String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      //小数点后有几位小数
      return (num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    } else {
      return (num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    }
  }

  @override
  void initState() {
    //充电站
    getHDKGoodsListUrl();
    super.initState();
  }

  /*好单库商品筛选*/
  getHDKGoodsListUrl() async {
    FormData data = new FormData.fromMap({
      'type': widget.type,
      'cid': widget.cid,
      'back': '10',
      'min_id': min_id
    });
    Response<String> response =
        await HttpUtil().post(Api.GetHDKGoodsListUrl, data: data);
    Map userMap = json.decode(response.data);
    // print(userMap);
    HDKListModelEntity itemEntity = new HDKListModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          if (min_id == 1) {
            shopData.clear();
            shopData = itemEntity.data;
            min_id = itemEntity.min_id;
            print(min_id);
          } else {
            min_id = itemEntity.min_id;
            shopData.addAll(itemEntity.data);
          }
        });
      }
    }
  }
}
